﻿Imports System.IO
Imports System.Text
Imports System.Xml
Imports Mysoft.Map.Data
Imports System.Collections.Specialized

Partial Public Class LogExportsServices
    Inherits System.Web.UI.Page

    Private erpAppName As String = "ErpSystem"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        '（StartDate）,结束日期（EndDate）,用户名（UserName）,密码(Password),客户名称(CustomerName),产品名称（ProductName）
        Dim queryString As NameValueCollection = HttpUtility.ParseQueryString(Request.Url.Query)
        Dim startDate As String = queryString("StartDate")
        Dim endDate As String = queryString("EndDate")
        Dim userName As String = queryString("UserName")
        Dim passWord As String = queryString("Password")
        Dim customerName As String = queryString("CustomerName")
        Dim productName As String = queryString("ProductName")

        If CheckArgs(startDate, endDate, userName, passWord, customerName, productName) = False Then
            Response.End()
            Response.Close()
            Return
        End If

        Dim dtBeginDate As Date = CType(startDate, Date)
        Dim dtEndDate As Date = CType(endDate, Date)

        '调用导出方法
        Dim result As String = Mysoft.Map.LMS.LogExports.ExportToFile(dtBeginDate, dtEndDate, userName, passWord, customerName, productName)
        Dim xmlDom As New XmlDocument
        xmlDom.LoadXml(result)

        If xmlDom.DocumentElement IsNot Nothing AndAlso xmlDom.DocumentElement.Attributes.GetNamedItem("result") IsNot Nothing Then
            If xmlDom.DocumentElement.Attributes.GetNamedItem("result").Value = "false" Then
                Response.Write(result)
                Response.End()
                Response.Close()
                Return
            Else
                If xmlDom.DocumentElement.Attributes.GetNamedItem("filename") IsNot Nothing Then
                    Dim fileName As String = xmlDom.DocumentElement.Attributes.GetNamedItem("filename").Value
                    Dim fileInfo As FileInfo = New FileInfo(Server.MapPath("\TempFiles\LMS\Export\" & fileName))

                    If Not fileInfo.Exists Then
                        Response.Write("<xml result=""false"" errormessage=""导出文件不存在！""></xml>")
                        Response.End()
                        Response.Close()
                        Return
                    End If

                    '输出文件
                    Using fs As FileStream = File.OpenRead(fileInfo.FullName)
                        Dim dataLength As Long = fs.Length
                        Dim bufferSize As Integer = 1024 * 1024
                        Dim buffer(bufferSize - 1) As Byte

                        Response.Clear()
                        Response.ContentType = "application/octet-stream"
                        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8))
                        Response.AppendHeader("DataLength", dataLength.ToString())
                        Response.ContentEncoding = Encoding.UTF8
                        Dim responseDataLength As Long = 0
                        While dataLength > 0 AndAlso Response.IsClientConnected
                            Dim readLength As Integer = fs.Read(buffer, 0, bufferSize)
                            Response.OutputStream.Write(buffer, 0, readLength)
                            Response.Flush()
                            responseDataLength += readLength
                            dataLength -= readLength
                        End While

                        Response.End()
                        Response.Close()
                    End Using
                End If
            End If

        End If


    End Sub

    Private Function CheckArgs(ByVal startDate As String, ByVal endDate As String, ByVal userName As String, ByVal passWord As String, ByVal customerName As String, ByVal productName As String) As Boolean

        If Not IsDate(startDate) Then
            If startDate Is Nothing AndAlso startDate = "" Then
                Response.Write("<xml result=""false"" errormessage=""开始时间不能为空！""></xml>")
            Else
                Response.Write("<xml result=""false"" errormessage=""开始时间格式错误！""></xml>")
            End If

            Return False
        End If

        If Not IsDate(endDate) Then
            If endDate Is Nothing AndAlso endDate = "" Then
                Response.Write("<xml result=""false"" errormessage=""结束时间不能为空！""></xml>")
            Else
                Response.Write("<xml result=""false"" errormessage=""结束时间格式错误！""></xml>")
            End If

            Return False
        End If

        If userName IsNot Nothing AndAlso userName.Trim() = "" Then
            Response.Write("<xml result=""false"" errormessage=""用户名称不能为空！""></xml>")

            Return False
        End If

        If passWord IsNot Nothing AndAlso passWord.Trim() = "" Then
            Response.Write("<xml result=""false"" errormessage=""密码不能为空！""></xml>")

            Return False
        End If

        If customerName IsNot Nothing AndAlso customerName.Trim() = "" Then
            Response.Write("<xml result=""false"" errormessage=""客户名称不能为空！""></xml>")
            Return False
        End If

        If productName IsNot Nothing AndAlso productName.Trim() = "" Then
            Response.Write("<xml result=""false"" errormessage=""产品名称不能为空！""></xml>")
            Return False
        End If

        '校验用户名和密码
        Dim dePassword = MySoft.Map.Security.Cryptography.DeCode(passWord)
        Dim md5Password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(dePassword, "md5")

        If Not VerifyUserLogin(userName, md5Password) Then
            Response.Write("<xml result=""false"" errormessage=""用户名或密码错误！""></xml>")
            Return False
        End If

        '校验客户和产品所属关系
        '取客户信息、产品信息
        Dim dt As DataTable = MySoft.Map.LMS.CustomerProduct.GetCustomerProduct()
        If dt IsNot Nothing AndAlso dt.Rows(0)(0) IsNot Nothing AndAlso dt.Rows(0)(1) IsNot Nothing Then
            If dt.Rows(0)(0).ToString().Trim().Length > 0 AndAlso dt.Rows(0)(1).ToString().Trim().Length > 0 Then
                If customerName.ToLower() = dt.Rows(0)("Customer").ToString().ToLower() AndAlso productName.ToLower() = dt.Rows(0)("Product").ToString().ToLower() Then
                    Return True
                End If
            End If
        End If

        Response.Write("<xml result=""false"" errormessage=""产品：" + productName + "，不属于客户" + customerName + "！""></xml>")
        Return False
    End Function

    Private Function VerifyUserLogin(ByVal strUserCode As String, ByVal strPassWord As String) As Boolean
        '通过普通登录方法验证用户名与密码的正确性
        Try
            Dim result As String = MySoft.Map.LMS.LmsLogin.UserLogin(strUserCode, strPassWord, False)
            Return (result.Length = 0)
            ' Return MySoft.Map.Security.MyLogin.NormalLogin(strUserCode, strPassWord)
        Catch ex As Exception
            '验证失败则返回False
            Return False
        End Try
    End Function

End Class